/**
 * Copyright (c) 2015-2016, Chill Zhuang 庄骞 (smallchill@163.com).
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ledi.guns.core.util;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;

public class DateUtil {

	private static String default_timezone = "CST";

	/**
	 * 获取YYYY格式
	 *
	 * @return
	 */
	public static String getYear() {

		return formatDate(new Date(), "yyyy");
	}

	/**
	 * 获取YYYY格式
	 *
	 * @return
	 */
	public static String getYear(Date date) {

		return formatDate(date, "yyyy");
	}

	/**
	 * 获取YYYY-MM-DD格式
	 *
	 * @return
	 */
	public static String getDay() {

		return formatDate(new Date(), "yyyy-MM-dd");
	}

	/**
	 * 获取YYYY-MM-DD格式
	 *
	 * @return
	 */
	public static String getDay(Date date) {

		return formatDate(date, "yyyy-MM-dd");
	}

	/**
	 * 获取YYYYMMDD格式
	 *
	 * @return
	 */
	public static String getDays() {

		return formatDate(new Date(), "yyyyMMdd");
	}

	/**
	 * 获取YYYYMMDD格式
	 *
	 * @return
	 */
	public static String getDays(Date date) {

		return formatDate(date, "yyyyMMdd");
	}

	/**
	 * 获取YYYYMMDDHH格式
	 *
	 * @return
	 */
	public static String getHouces() {

		return formatDate(new Date(), "yyyyMMddHH");
	}

	/**
	 * 获取YYYY-MM-DD HH:mm:ss格式
	 *
	 * @return
	 */
	public static String getTime() {

		return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 获取YYYY-MM-DD HH:mm:ss.SSS格式
	 *
	 * @return
	 */
	public static String getMsTime() {

		return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
	}

	/**
	 * 获取YYYYMMDDHHmmss格式
	 *
	 * @return
	 */
	public static String getAllTime() {

		return formatDate(new Date(), "yyyyMMddHHmmss");
	}

	/**
	 * 获取YYYY-MM-DD HH:mm:ss格式
	 *
	 * @return
	 */
	public static String getTime(Date date) {

		return formatDate(date, "yyyy-MM-dd HH:mm:ss");
	}

	public static String formatDate(Date date, String pattern) {

		String formatDate = null;
		if (StringUtils.isNotBlank(pattern)) {
			formatDate = DateFormatUtils.format(date, pattern);
		} else {
			formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
		}
		return formatDate;
	}

	/**
	 * @Title: compareDate
	 * @Description:(日期比较，如果s>=e 返回true 否则返回false)
	 * @param s
	 * @param e
	 * @return boolean
	 * @throws
	 * @author
	 *         luguosui
	 */
	public static boolean compareDate(String s, String e) {

		if (parseDate(s) == null || parseDate(e) == null) {
			return false;
		}
		return parseDate(s).getTime() >= parseDate(e).getTime();
	}

	/**
	 * 格式化日期
	 *
	 * @return
	 */
	public static Date parseDate(String date) {

		return parse(date, "yyyy-MM-dd");
	}

	/**
	 * 格式化日期
	 *
	 * @return
	 */
	public static Date parseTime(String date) {

		return parse(date, "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 格式化日期
	 *
	 * @return
	 */
	public static Date parseDate1(String date) {

		return parse(date, "yyyyMMddHHmmss");
	}

	/**
	 * 格式化日期
	 *
	 * @return
	 */
	public static Date parse(String date, String pattern) {

		try {
			return DateUtils.parseDate(date, pattern);
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 格式化日期
	 *
	 * @return
	 */
	public static String format(Date date, String pattern) {

		return DateFormatUtils.format(date, pattern);
	}

	/**
	 * 把日期转换为Timestamp
	 *
	 * @param date
	 * @return
	 */
	public static Timestamp format(Date date) {

		return new Timestamp(date.getTime());
	}

	/**
	 * 校验日期是否合法
	 *
	 * @return
	 */
	public static boolean isValidDate(String s) {

		return parse(s, "yyyy-MM-dd HH:mm:ss") != null;
	}

	/**
	 * 校验日期是否合法
	 *
	 * @return
	 */
	public static boolean isValidDate(String s, String pattern) {

		return parse(s, pattern) != null;
	}

	public static int getDiffYear(String startTime, String endTime) {

		DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
		try {
			int years = (int) ((fmt.parse(endTime).getTime() - fmt.parse(
					startTime).getTime()) / (1000 * 60 * 60 * 24) / 365);
			return years;
		} catch (Exception e) {
			// 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
			return 0;
		}
	}

	/**
	 * <li>功能描述：时间相减得到天数
	 *
	 * @param beginDateStr
	 * @param endDateStr
	 * @return long
	 * @author Administrator
	 */
	public static long getDaySub(String beginDateStr, String endDateStr) {

		long day = 0;
		SimpleDateFormat format = new SimpleDateFormat(
				"yyyy-MM-dd");
		Date beginDate = null;
		Date endDate = null;

		try {
			beginDate = format.parse(beginDateStr);
			endDate = format.parse(endDateStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		day = (endDate.getTime() - beginDate.getTime()) / (24 * 60 * 60 * 1000);
		// System.out.println("相隔的天数="+day);

		return day;
	}

	public static Date addDaysToDate(Date date, int dayNum) {

		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.add(Calendar.DATE, dayNum);
		return c.getTime();
	}

	/**
	 * Return the date x months later. e.g. current date is 2010-1-1
	 * addMonthsToDate(date,3) is 2010-4-1 If months ago is required, set the
	 * monthNum parameter to negative
	 *
	 * @param date
	 *            input date
	 * @param monthNum
	 *            input the number of month
	 * @return new date
	 * @author lijianfeng
	 */
	public static Date addMonthsToDate(Date date, int monthNum) {

		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.add(Calendar.MONTH, monthNum);
		return c.getTime();
	}

	/**
	 * 得到n天之后的日期
	 *
	 * @param days
	 * @return
	 */
	public static String getAfterDayDate(String days) {

		int daysInt = Integer.parseInt(days);

		Calendar canlendar = Calendar.getInstance(); // java.util包
		canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
		Date date = canlendar.getTime();

		SimpleDateFormat sdfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateStr = sdfd.format(date);

		return dateStr;
	}

	public static Date formate(Date date, boolean flag) {

		// 处理时间
		Calendar instance = Calendar.getInstance();
		instance.setTime(date);
		if (flag) {
			instance.set(instance.get(Calendar.YEAR), instance.get(Calendar.MONTH), instance.get(Calendar.DATE),
					0, 0, 0);
		} else {
			instance.set(instance.get(Calendar.YEAR), instance.get(Calendar.MONTH), instance.get(Calendar.DATE),
					23, 59, 59);
		}

		date = instance.getTime();
		return date;
	}

	public static List<Date> formateDate(Date from, Date to) {

		if (from == null || to == null) {
			return null;
		}
		// 处理时间
		Calendar instance = Calendar.getInstance();
		instance.setTime(from);
		instance.set(instance.get(Calendar.YEAR), instance.get(Calendar.MONTH), instance.get(Calendar.DATE),
				0, 0, 0);
		from = instance.getTime();
		instance.setTime(to);
		instance.set(instance.get(Calendar.YEAR), instance.get(Calendar.MONTH), instance.get(Calendar.DATE),
				23, 59, 59);
		to = instance.getTime();

		List<Date> list = new ArrayList<Date>();
		list.add(from);
		list.add(to);
		return list;
	}

	/**
	 * 得到n天之后是周几
	 *
	 * @param days
	 * @return
	 */
	public static String getAfterDayWeek(String days) {

		int daysInt = Integer.parseInt(days);

		Calendar canlendar = Calendar.getInstance(); // java.util包
		canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
		Date date = canlendar.getTime();

		SimpleDateFormat sdf = new SimpleDateFormat("E");
		String dateStr = sdf.format(date);

		return dateStr;
	}

	/**
	 * 格式化Oracle Date
	 *
	 * @param value
	 * @return
	 */
	// public static String buildDateValue(Object value){
	// if(Func.isOracle()){
	// return "to_date('"+ value +"','yyyy-mm-dd HH24:MI:SS')";
	// }else{
	// return Func.toStr(value);
	// }
	// }

	/**
	 * 收集起始时间到结束时间之间所有的时间并以字符串集合方式返回
	 *
	 * @param start
	 * @param end
	 * @return
	 */
	public static List<String> collectLocalDates(LocalDate start, LocalDate end) {

		// 用起始时间作为流的源头，按照每次加一天的方式创建一个无限流
		return Stream.iterate(start, localDate -> localDate.plusDays(1))
				// 截断无限流，长度为起始时间和结束时间的差+1个
				.limit(ChronoUnit.DAYS.between(start, end) + 1)
				// 由于最后要的是字符串，所以map转换一下
				.map(LocalDate::toString)
				// 把流收集为List
				.collect(Collectors.toList());
	}

	/**
	 * 收集起始时间到结束时间之间所有的月份并以字符串集合方式返回
	 *
	 * @param start
	 * @param end
	 * @return
	 */
	public static List<String> collectLocalMonthDates(LocalDate start, LocalDate end) {

		// 用起始时间作为流的源头，按照每次加一个月的方式创建一个无限流
		return Stream.iterate(start, localDate -> localDate.plusMonths(1))
				// 截断无限流，长度为起始时间和结束时间的差+1个
				.limit(ChronoUnit.MONTHS.between(start, end) + 1)
				// 由于最后要的是字符串，所以map转换一下
				.map(LocalDate::toString)
				// 把流收集为List
				.collect(Collectors.toList());
	}

	/**
	 * 收集起始时间到结束时间之间所有的月份并以字符串集合方式返回
	 *
	 * @param start
	 * @param end
	 * @return
	 */
	public static List<String> collectLocalDayDates(LocalDateTime start, LocalDateTime end) {

		// 用起始时间作为流的源头，按照每次加一小时的方式创建一个无限流
		return Stream.iterate(start, localDate -> localDate.plus(1L, ChronoUnit.HOURS))
				// 截断无限流，长度为起始时间和结束时间的差+1个
				.limit(ChronoUnit.HOURS.between(start, end) + 1)
				// 由于最后要的是字符串，所以map转换一下
				.map(LocalDateTime::toString)
				// 把流收集为List
				.collect(Collectors.toList());
	}

	public static void main(String[] args) {

		System.out.println(getTime(new Date()));
		System.out.println(getAfterDayWeek("3"));
	}

	/**
	 * Set the time component as the last seconds of the day.
	 * <p/>
	 * The Time Component of the date returned will be set to 23:59:59.
	 * <p/>
	 *
	 * @param date
	 *            The Date to get the last seconds
	 * @return The date with the time component set to the last seconds of the
	 *         day.
	 */
	public static Date getEndOfDay(Date date) {

		Calendar cal = Calendar.getInstance();
		cal.setTime(date);

		// Clear the time component
		cal.set(Calendar.HOUR_OF_DAY, cal
				.getActualMaximum(Calendar.HOUR_OF_DAY));
		cal.set(Calendar.MINUTE, cal.getActualMaximum(Calendar.MINUTE));
		cal.set(Calendar.SECOND, cal.getActualMaximum(Calendar.SECOND));
		cal.set(Calendar.MILLISECOND, cal
				.getActualMaximum(Calendar.MILLISECOND));

		// System.out.println( "cal.toString() = " + cal.toString() );

		return cal.getTime();
	}

	/**
	 * Get the start day of month of the input date. e.g. input date 27-03-2007
	 * return date 01-03-2007 00:00:00
	 *
	 * @param aDate
	 *            aDate
	 * @return start day of month with time 00:00:00
	 */
	public static Date getStartDayOfMonth(Date aDate) {

		Calendar cal = Calendar.getInstance();
		cal.setTime(aDate);
		cal.set(Calendar.DAY_OF_MONTH, cal
				.getActualMinimum(Calendar.DAY_OF_MONTH));
		return DateUtil.getStartOfDay(cal.getTime());
	}

	/**
	 * Set the time component as the start of the day.
	 * <p/>
	 * The Time Component of the date returned will be set to 00:00:00.
	 * <p/>
	 *
	 * @param date
	 *            The Date to get the start of the day
	 * @return The date with the time component reset to 00:00:00.
	 */
	public static Date getStartOfDay(Date date) {

		Calendar cal = Calendar.getInstance();
		cal.setTime(date);

		// Clear the time component
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH) + 1;
		int day = cal.get(Calendar.DAY_OF_MONTH);

		return getDate(year, month, day);
	}

	/**
	 * Get the start day of month of the input date added the specified (signed)
	 * amount to the given field, based on the calendar's rules.
	 * <p>
	 * For example, to get start of the last month, it can be achieved by calling:
	 * <p>
	 * getStartDayOfMonth(aDate, Calendar.MONTH, -1).
	 * <p>
	 * e.g. input <br>
	 * date: 27-03-2007,<br>
	 * field: Calendar.MONTH,<br>
	 * offset: -1<br>
	 * return date: 01-02-2007 00:00:00
	 * <p>
	 *
	 * @param aDate
	 *            The date to perform the arithmetic function on
	 * @param field
	 *            A Calendar constant to retrieve the field value from the
	 *            Date object.
	 * @param offset
	 *            the amount of date or time to be added to the field
	 * @return The date as a result of the execution of the arithmetic function.
	 */
	public static Date getStartDayOfMonth(Date aDate, int field, int offset) {

		return getStartDayOfMonth(DateUtil.add(aDate, field, offset));
	}

	/**
	 * Get the end day of month of the input date. e.g. input date 27-03-2007
	 * return date 31-03-2007 23:59:59
	 *
	 * @param aDate
	 *            aDate
	 * @return end day of month with time 23:59:59
	 */
	public static Date getEndDayOfMonth(Date aDate) {

		Calendar cal = Calendar.getInstance();
		cal.setTime(aDate);
		cal.set(Calendar.DAY_OF_MONTH, cal
				.getActualMaximum(Calendar.DAY_OF_MONTH));
		return DateUtil.getEndOfDay(cal.getTime());
	}

	/**
	 * Returns the date instance based on the current system date and default
	 * timezone.
	 *
	 * @return Current System date.
	 */
	public static Date getDate() {

		TimeZone tz = TimeZone.getTimeZone(default_timezone);
		Calendar calendar = Calendar.getInstance(tz);
		return calendar.getTime();
	}

	/**
	 * Return the Date instance with the provided year, month ( 1 - 12 ), and
	 * day ( 1 - 31 ) values.
	 * <p/>
	 * The date value will roll over when given a value that is greater than the max possible. Eg. when getDate( 2002,
	 * 10, 32 ) is provided, the Date instance will be 1st Nov 2002.
	 * <p/>
	 *
	 * @param year
	 *            Year
	 * @param month
	 *            Month ( 1 - 12 )
	 * @param day
	 *            Day( 1 - 31 )
	 * @return The Date instance created.
	 */
	public static Date getDate(int year, int month, int day) {

		Calendar cal = Calendar.getInstance();

		// Clear all fields first
		cal.clear();

		cal.set(year, month - 1, day);

		return cal.getTime();
	}

	/**
	 * Date Arithmetic function. Adds the specified (signed) amount of time to
	 * the given time field, based on the calendar's rules.
	 * <p>
	 * For example, to subtract 5 days from a specific date, it can be achieved by calling:
	 * <p>
	 * DateUtil.add(date, Calendar.DATE, -5).
	 * <p>
	 *
	 * @param date
	 *            The date to perform the arithmetic function on
	 * @param field
	 *            A Calendar constant to retrieve the field value from the
	 *            Date object. Same as for {@link #get get()}.
	 * @param amount
	 *            the amount of date or time to be added to the field
	 * @return The date as a result of the execution of the arithmetic function.
	 */
	public static Date add(Date date, int field, int amount) {

		TimeZone tz = TimeZone.getTimeZone(default_timezone);
		Calendar cal = Calendar.getInstance(tz);
		cal.setTime(date);
		cal.add(field, amount);

		return cal.getTime();
	}
}
